<?php

namespace App\Trip\Tencent\Cloud\Market\IdCard;

use App\Trip\Passengers\IdentityCodeNameCheckRes;
use App\Trip\Passengers\Interfaces\IdentityCodeNameCheckResInterface;
use Carbon\Carbon;
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class IdCheckPost implements IdentityCodeNameCheckResInterface
{
    private string $url;
    private string $cache_key;
    // 云市场分配的密钥Id
    private string $secretId;
    private string $secretKey;
    private string $source = 'market';
    private string $identity_code;
    private string $truename;

    public function __construct(string $identity_code, string $truename)
    {
        $this->url           = config('idcard.check.url');
        $this->secretId      = config('idcard.check.secretId');
        $this->secretKey     = config('idcard.check.secretKey');
        $today               = Carbon::today()->toDateString();
        $this->cache_key     = "IdCheckPost:{$identity_code}:{$today}";
        $this->truename      = $truename;
        $this->identity_code = $identity_code;
    }

    /**
     * @throws GuzzleException
     * @throws Exception
     */
    public function query(): IdentityCodeNameCheckRes
    {
        if (Cache::get($this->cache_key) > 5) {
            return new IdentityCodeNameCheckRes(['error_msg' => '今日该证件查询已达上限']);
        }

        Cache::increment($this->cache_key);
        // 签名
        $datetime   = gmdate('D, d M Y H:i:s T');
        $signStr    = sprintf("x-date: %s\nx-source: %s", $datetime, $this->source);
        $sign       = base64_encode(hash_hmac('sha1', $signStr, $this->secretKey, true));
        $auth       = sprintf('hmac id="%s", algorithm="hmac-sha1", headers="x-date x-source", signature="%s"', $this->secretId, $sign);
        $bodyParams = [
            'cardNo'   => $this->identity_code,
            'realName' => $this->truename,
        ];
        $headers    = [
            'X-Source'      => $this->source,
            'X-Date'        => $datetime,
            'Authorization' => $auth,
        ];
        $client     = new Client();
        $resp       = $client->post($this->url, [
            'headers'     => $headers,
            'form_params' => $bodyParams,
        ]);

        $content = $resp->getBody()->getContents();
        Log::info("IdCheckPost:".$content);
        $response = json_decode($content, true) ?: [];
        if (!isset($response['error_code'])) {
            Log::error("IdCheckPost Error:{$this->truename}:{$this->identity_code}:{$content}");
            throw new Exception("查询失败,{$this->truename}:{$this->identity_code}");
        }

        $result = $response['result'];
        $isOk   = $result['isok'] === true;

        return new IdentityCodeNameCheckRes([
            'check_state' => $isOk ? 1 : 0,
            'info'        => $result['IdCardInfor'],
        ]);

    }

}